package com.zhiyou100.interceptor;

import com.zhiyou100.exception.LoginException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截器
 * <p>
 * spring-webmvc-4.3.2.RELEASE.jar 不是默认方法
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-10-14 22:35
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String user = "user";
        //判断session中是否有user
        if (request.getSession().getAttribute(user) == null) {
            //没有登陆：抛出异常
            throw new LoginException("必须登陆才能访问！");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

